package com.scpii.universal.pns.service;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.xwork.StringUtils;
import org.springframework.stereotype.Service;

import com.scpii.universal.constant.GenericConstants;
import com.scpii.universal.pns.dao.PnsAppDao;
import com.scpii.universal.pns.dao.PnsGroupDao;
import com.scpii.universal.pns.dao.PnsMessageDao;
import com.scpii.universal.pns.dao.PnsUserDao;
import com.scpii.universal.pns.dao.PnsUserGroupDao;
import com.scpii.universal.pns.dao.PnsUserMessageDao;
import com.scpii.universal.pns.dao.UserAppDtoDao;
import com.scpii.universal.pns.dto.MessageDto;
import com.scpii.universal.pns.dto.MessgeBodyDto;
import com.scpii.universal.pns.dto.MsgManageDto;
import com.scpii.universal.pns.dto.UserAppDto;
import com.scpii.universal.pns.entity.PnsApp;
import com.scpii.universal.pns.entity.PnsGroup;
import com.scpii.universal.pns.entity.PnsMessage;
import com.scpii.universal.pns.entity.PnsUser;
import com.scpii.universal.pns.entity.PnsUserGroup;
import com.scpii.universal.pns.entity.PnsUserMessage;
import com.scpii.universal.util.EhCacheManager;
import com.scpii.universal.util.ImgAndFilePath;
import com.scpii.universal.util.StreamUtil;

@Service
public class PnsMessageServiceImpl extends
		PnsBaseServiceImpl<PnsMessage, Integer> implements PnsMessageService {

	@Resource
	private PnsMessageDao pnsMessageDao;
	@Resource
	private PnsGroupDao pnsGroupDao;
	@Resource
	private PnsUserGroupDao pnsUserGroupDao;
	@Resource
	private PnsUserDao pnsUserDao;
	@Resource
	private PnsUserMessageDao pnsUserMessageDao;
	@Resource
	private UserAppDtoDao userAppDtoDao;
	@Resource
	private PnsAppDao pnsAppDao;

	@Resource
	public void setBaseDao(PnsMessageDao pnsMessageDao) {
		super.setBaseDao(pnsMessageDao);
	}

	private Integer BUILD_PLATFORM = 1;

	/**
	 * 
	 * 推送消息 初始化页面
	 * 
	 * @author zhangqiang 2012-11-20上午09:28:38
	 */
	public List<PnsGroup> getPnsInit(Integer enterpId, Integer appId) {
		// 获取组信息
		Map<String, Object> map = new HashMap<String, Object>();
		String sql = "select t from PnsGroup t where t.appid= :appId and t.parentGroupId=:parentGroupId";
		map.put("appId", appId);
		map.put("parentGroupId", 0);
		List<PnsGroup> groupInfo = pnsGroupDao.findByHql(sql, 0, 0, map, null);
		return groupInfo;
	}

	/**
	 * 获取目标用户群体的信息，
	 * 
	 * @param request
	 * @param response
	 */
	public List<PnsUser> getUserinfo(PnsUser condition, Integer pageNo,
			Integer pageSize, Integer appId) {
		StringBuffer hql = new StringBuffer(
				" select u.userId, u.deviceId,u.deviceType,u.createDate from PnsUser u ,PnsUserApp t1,PnsApp t2 where t1.userId= u.userId and t1.appSerial=t2.appSerial and t2.appId=:appId ");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("appId", appId.toString());
		if (condition != null) {
			if (condition.getType() == null || "".equals(condition.getType())) {
				if (condition.getDeviceType() != null) {
					hql.append(" and u.deviceType =:deviceType");
					map.put("deviceType", condition.getDeviceType());
				}
				if (condition.getDeviceId() != null
						&& !"".equals(condition.getDeviceId())) {
					hql.append(" and u.deviceId =:deviceId");
					map.put("deviceId", condition.getDeviceId());
				}
				if (condition.getCreateStartDate() != null
						&& !"".equals(condition.getCreateStartDate())) {
					hql.append(" and u.createDate >= to_date(:createStartDate,'yyyy-mm-dd HH24:MI:SS') ");
					map.put("createStartDate", condition.getCreateStartDate());
				}
				if (condition.getCreateEndDate() != null
						&& !"".equals(condition.getCreateEndDate())) {
					hql.append(" and u.createDate <= to_date(:createEndDate,'yyyy-mm-dd HH24:MI:SS') ");
					map.put("createEndDate", condition.getCreateEndDate());
				}
			}
		}

		List<PnsUser> list = pnsUserDao.findByHql(hql.toString(), pageNo,
				pageSize, map, null);
		return list;
	}

	/**
	 * 保存新建的推送消息 目标组
	 * 
	 * @param request
	 * @param response
	 */
	public Integer saveGroupInfo(PnsGroup pnsGroup, String userIds,
			Integer appId) {

		try {
			pnsGroup.setBuildPlatform(BUILD_PLATFORM);
			pnsGroup.setAppId(appId);
			pnsGroup.setGroupName(new String(pnsGroup.getGroupName().getBytes(
					"ISO8859-1"), "utf-8"));
			pnsGroupDao.save(pnsGroup);

			if (userIds != null && !"".equals(userIds)) {
				String[] ids = userIds.split(",");

				for (int i = 0; i < ids.length; i++) {
					if (ids[i] != null && !"".equals(ids[i])) {
						PnsUserGroup pug = new PnsUserGroup();
						pug.setUserId(Integer.parseInt(ids[i]));
						pug.setGroupId(pnsGroup.getGroupId());
						pnsUserGroupDao.save(pug);
					}
				}

			}

		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}

		return pnsGroup.getGroupId();
	}

	/**
	 * 保存推送信息
	 * 
	 * @param request
	 * @param response
	 * 
	 * @throws Exception
	 */
	public Integer saveMessageInfo(MessageDto msgDto,
			HttpServletRequest request, String groupIds, int enterpId,
			Integer appId, String webRoot) throws Exception {

		PnsMessage pnsMsg = null;
		boolean flag = true;
		String absolutpath = request.getSession().getServletContext()
				.getRealPath("/");
		String serverRoot = EhCacheManager.getObject(
				GenericConstants.SERVER_URL_PREFIX).toString();

		if (msgDto != null) {
			pnsMsg = new PnsMessage();
			// 保存基本信息
			pnsMsg.setAppId(appId.toString());
			// 1：4s, 2:universal
			pnsMsg.setBuildPlatform(BUILD_PLATFORM);
			pnsMsg.setStartDate(msgDto.getStartDate());
			pnsMsg.setExpireDate(msgDto.getExpireDate());
			pnsMsg.setSummary(msgDto.getSummary());
			pnsMsg.setTitle(msgDto.getTitle());
			pnsMsg.setIcon("default");
			pnsMsg.setCreateDate(new Date());
			pnsMsg.setMessageStatus(1);
			if (msgDto.getMessageId() != null) {
				// update
				pnsMsg.setMessageId(msgDto.getMessageId());
				pnsMessageDao.update(pnsMsg);
				flag = false;
			} else {
				pnsMessageDao.save(pnsMsg);
			}
			// 处理内容
			int msgId = pnsMsg.getMessageId();

			// 处理
			if (!StringUtils.isBlank(msgDto.getIcon())
					&& !"default".equalsIgnoreCase(msgDto.getIcon())) {
				// 图片信息
				// String
				// serverRoot=EhCacheManager.getObject(GenericConstants.SERVER_URL_PREFIX).toString();
				String filePath = absolutpath.replace("\\universalWeb", "")
						+ webRoot + File.separator + ImgAndFilePath.PNS
						+ File.separator + "push_" + msgId + "_icon.png";
				String tempFile = absolutpath.replace("\\universalWeb", "")
						+ msgDto.getIcon().replace(serverRoot, "");
				if (tempFile.contains("WORKDIR/TEMP/")) {
					StreamUtil.uploadActiveImgs(new File(tempFile), filePath);
					// 删除临时文件
					if (new File(tempFile).exists()) {
						new File(tempFile).delete();
					}
				}
				pnsMsg.setIcon((webRoot + ImgAndFilePath.PNS + "\\push_"
						+ msgId + "_icon.png").replace("\\", "/"));
			}

			// 处理内容

			StringBuffer bodyMsg = new StringBuffer("[");
			List<MessgeBodyDto> bodyContent = msgDto.getBodyDto();

			if (bodyContent != null && bodyContent.size() > 0) {
				int index = 0;
				for (MessgeBodyDto mbDto : bodyContent) {
					if (mbDto != null) {
						// 文本信息
						if (mbDto.getContentType() == 0) {
							bodyMsg.append("{\"type\":\"0\",");
							// 替换 回车 换行
							String content = mbDto.getContent().replaceAll(
									"\n", "\\\\n");
							content = content.replaceAll("\r", "\\\\r");
							// content=content.replaceAll("\'","\\\\'");
							content = content.replaceAll("\"", "\\\\\"");
							bodyMsg.append("\"content\":\"" + content + "\"},");
						} else if (mbDto.getContentType() == 1) {
							// 图片信息
							String filePath = absolutpath.replace(
									"\\universalWeb", "")
									+ webRoot
									+ File.separator
									+ ImgAndFilePath.PNS
									+ File.separator
									+ "push_"
									+ msgId
									+ "_"
									+ index + ".png";

							String tempFile = absolutpath.replace(
									"\\universalWeb", "")
									+ mbDto.getContent()
											.replace(serverRoot, "");
							if (tempFile.contains("WORKDIR/TEMP/")) {
								StreamUtil.uploadActiveImgs(new File(tempFile),
										filePath);
								// 删除临时文件
								if (new File(tempFile).exists()) {
									new File(tempFile).delete();
								}
							}
							bodyMsg.append("{\"type\":\"1\",");
							bodyMsg.append("\"content\":\""
									+ (webRoot + ImgAndFilePath.PNS + "\\push_"
											+ msgId + "_" + index + ".png")
											.replace("\\", "/") + "\"},");

						} else if (mbDto.getContentType() == 2) {
							// 视频信息
							// 图片信息
							// String filePath =
							// request.getSession().getServletContext().getRealPath("/")
							// + "\\"
							// + ImgAndFilePath.PUSH_MSG_DIR + "push_" + msgId +
							// "_" + index + ".png";

							// String serverPath =
							// UtilTool.uploadImgFile(mbDto.getUpLoadFile(),
							// filePath);
							bodyMsg.append("{\"type\":\"2\",");
							bodyMsg.append("\"content\":\""
									+ mbDto.getContent() + "\"},");
						} else if (mbDto.getContentType() == 3) {
							// 视频信息
							// 图片信息
							// String filePath =
							// request.getSession().getServletContext().getRealPath("/")
							// + "\\"
							// + ImgAndFilePath.PUSH_MSG_DIR + "push_" + msgId +
							// "_" + index + ".png";

							// String serverPath =
							// UtilTool.uploadImgFile(mbDto.getUpLoadFile(),
							// filePath);
							bodyMsg.append("{\"type\":\"3\",");
							bodyMsg.append("\"content\":\""
									+ mbDto.getContent() + "\"},");
						}
						index++;
					}
				}
			}
			String bodyMsgs = bodyMsg.toString();
			bodyMsgs = bodyMsgs.substring(0, bodyMsgs.lastIndexOf(",")) + "]";
			// 将最后一个分号去掉
			// 更新内容
			pnsMsg.setBody(bodyMsgs);
			pnsMessageDao.update(pnsMsg);

			// 更新用户和信息表
			if (!flag) {
				String hql = "select t from PnsUserMessage t where t.messageId="
						+ pnsMsg.getMessageId();
				List<PnsUserMessage> userMessageList = pnsUserMessageDao
						.findByHql(hql, 0, 0, null, null);
				for (PnsUserMessage userMessage : userMessageList) {
					userMessage.setBody(pnsMsg.getBody());
					userMessage.setStartDate(pnsMsg.getStartDate());
					userMessage.setExpireDate(pnsMsg.getExpireDate());
					userMessage.setSummary(pnsMsg.getSummary());
					userMessage.setTitle(pnsMsg.getTitle());
					userMessage.setIcon(pnsMsg.getIcon());
					pnsUserMessageDao.update(userMessage);
				}
			}

		}
		return pnsMsg.getMessageId();
	}

	public void saveMsgGroup(Integer messageId, Integer enterpId, Integer appId) {
		// 去掉 组内重复的人员。
		// 获取组
		Map<String, Object> map = new HashMap<String, Object>();
		String sql = "select t from PnsGroup t where t.messageId= :messageId ";
		map.put("messageId", messageId);
		List<PnsGroup> groupInfo = pnsGroupDao.findByHql(sql, 0, 0, map, null);

		List<Integer> gidList = new ArrayList<Integer>();
		if (groupInfo != null && groupInfo.size() > 0) {
			for (PnsGroup gid : groupInfo) {
				gidList.add(gid.getGroupId());
			}
			try {
				String hql = " select distinct new com.scpii.universal.pns.dto.UserAppDto(t1.userId,t2.deviceType) from PnsUserGroup t1,PnsUser t2 where  t1.userId=t2.userId  and t1.groupId in (:ids) ";
				map = new HashMap<String, Object>();
				// map.put("ids", gidList);
				List<UserAppDto> list = userAppDtoDao.findByHql(hql.toString(),
						0, 0, map, gidList);
				map.put("messageId", messageId);
				pnsUserMessageDao.updateByHql("DELETE_PNS_USER", map);
				// 获取appserival TODO
				// hql = " select t  from PnsApp t where t.appId=:appId ";
				// map = new HashMap<String, Object>();
				// map.put("appId", getAppId(enterpId));
				// List<PnsApp> appList = pnsAppDao.findByHql(hql.toString(), 0,
				// 0, map, gidList);
				// 將信息写入到 pns_user_message

				PnsUserMessage userMessage = null;
				PnsMessage pmg = pnsMessageDao.get(messageId);
				for (UserAppDto pnsU : list) {
					// 应哟Id
					userMessage = new PnsUserMessage();
					userMessage.setAppId(appId.toString());
					userMessage.setMessageId(messageId);
					userMessage.setUserId(pnsU.getUserId());
					userMessage.setDeviceType(pnsU.getDeviceType());
					userMessage.setBody(pmg.getBody());
					userMessage.setBuildPlatform(BUILD_PLATFORM);
					userMessage.setStartDate(pmg.getStartDate());
					userMessage.setExpireDate(pmg.getExpireDate());
					userMessage.setSummary(pmg.getSummary());
					userMessage.setTitle(pmg.getTitle());
					userMessage.setIcon(pmg.getIcon());
					userMessage.setMessageStatus(1);
					// 获取appserival TODO
					hql = " select t from PnsApp t where t.appId=:appId and t.buildPlatform=:buildPlatform ";
					map = new HashMap<String, Object>();
					map.put("appId", appId.toString());
					map.put("buildPlatform", BUILD_PLATFORM);
					List<PnsApp> appList = pnsAppDao.findByHql(hql.toString(),
							0, 0, map, null);
					int appSerial = appList.get(0).getAppSerial();
					if (appList != null && appList.size() > 0) {
						userMessage.setAppSerial(appSerial);
					}
					// userMessage.setAppSerial(93);
					userMessage.setCreateDate(new Date());

					pnsUserMessageDao.save(userMessage);

				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		//
	}

	/**
	 * 获取消息的条数
	 * 
	 * @param enterId
	 * @return
	 * @author zhangqiang 2012-11-26下午02:07:09
	 */
	public Integer getMessgetCount(Integer enterId, Integer appId) {
		StringBuffer hql = new StringBuffer(
				" select count(*) from PnsMessage u "
						+ "where u.appId=:appId and u.buildPlatform=:buildPlatform ");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("appId", appId.toString());
		map.put("buildPlatform", BUILD_PLATFORM);
		List<Long> list = pnsMessageDao.findByHqlCount(hql.toString(), 0, 0,
				map, null);
		if (list != null && list.size() == 1) {
			return list.get(0).intValue();
		} else {
			return 0;
		}
	}

	/**
	 * 获取消息信息
	 * 
	 * @param enterId
	 * @return
	 * @author zhangqiang 2012-11-26下午02:15:14
	 */
	public List<MsgManageDto> getPnsManage(Integer enterId, Integer pageNo,
			Integer pageSize, Integer appId) {

		// 获取消息
		StringBuffer hql = new StringBuffer(
				" select new PnsMessage(u.messageId,u.appId,u.buildPlatform,u.title,u.summary,u.startDate,u.expireDate,u.messageStatus) from PnsMessage u "
						+ "where u.appId=:appId and u.buildPlatform=:buildPlatform order by u.createDate desc");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("appId", appId.toString());
		map.put("buildPlatform", BUILD_PLATFORM);
		List<PnsMessage> messageList = pnsMessageDao.findByHql(hql.toString(),
				pageNo, pageSize, map, null);

		// 获取组信息
		// hql = new
		// StringBuffer(" select u.appId,u.buildPlatform,u.groupName,u.groupId from PnsGroup u "
		// +
		// "where u.appId=:appId and u.buildPlatform=:buildPlatform group by u.appId ");
		// map = new HashMap<String, Object>();
		// map.put("appId", getAppId(enterId));
		// map.put("buildPlatform", BUILD_PLATFORM);
		// List<PnsGroup> groupList = pnsGroupDao.findByHql(hql.toString(), 0,
		// 0, map, null);
		List<MsgManageDto> msgList = null;
		if (messageList != null && messageList.size() > 0) {
			msgList = new ArrayList<MsgManageDto>();
			MsgManageDto mDto = null;
			Date date = new Date();

			for (PnsMessage pMsg : messageList) {
				mDto = new MsgManageDto();

				map = new HashMap<String, Object>();
				String sql = "select t from PnsGroup t where t.messageId=:messageId and t.buildPlatform=1 and t.appId=:appId";
				map.put("appId", Integer.parseInt(pMsg.getAppId()));
				map.put("messageId", pMsg.getMessageId());
				List<PnsGroup> groupInfo = pnsGroupDao.findByHql(sql, 0, 0,
						map, null);
				if (groupInfo != null && groupInfo.size() > 0) {
					for (PnsGroup pnsg : groupInfo) {
						if (mDto.getGroupNames() == null) {
							mDto.setGroupNames(pnsg.getGroupName());
						} else {
							mDto.setGroupNames(pnsg.getGroupName() + ","
									+ mDto.getGroupNames());
						}
					}
				}

				mDto.setAppId(pMsg.getAppId());
				mDto.setBuildPlatform(pMsg.getBuildPlatform());
				mDto.setMessageId(pMsg.getMessageId());
				mDto.setTitle(pMsg.getTitle());
				mDto.setSummary(pMsg.getSummary());
				mDto.setStartDate(pMsg.getStartDate());
				mDto.setExpireDate(pMsg.getExpireDate());
				mDto.setMessageStatus(pMsg.getMessageStatus());
				// 正在发送中
				if (mDto.getStartDate().before(date)
						&& mDto.getExpireDate().after(date)) {
					mDto.setFlag(0);
				}
				// 还没开始
				if (mDto.getStartDate().after(date)) {
					mDto.setFlag(1);
				}
				// 已经结束
				if (mDto.getExpireDate().before(date)) {
					mDto.setFlag(2);
				}
				// 不可以发送
				if (mDto.getMessageStatus() != null) {
					if (mDto.getMessageStatus() == 1) {
						mDto.setFlag(1);
					}
				}
				msgList.add(mDto);
			}
		}
		return msgList;

	}

	public void delgroupByName(PnsGroup pnsGroup) {

		// 获取组
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("groupId", pnsGroup.getGroupId());
		try {
			List<PnsGroup> groupList = pnsGroupDao.getObjectByHql(
					"SELECT_GROUP_BY_NAME", map);
			PnsGroup group = null;
			if (groupList != null && groupList.size() > 0) {
				group = groupList.get(0);
				String hql = " select distinct new com.scpii.universal.pns.dto.UserAppDto(t1.userId,t2.deviceType) from PnsUserGroup t1,PnsUser t2 where  t1.userId=t2.userId  and t1.groupId=:groupId";
				List<UserAppDto> list = userAppDtoDao.findByHql(hql.toString(),
						0, 0, map, null);
				Map<String, Object> hashmap = new HashMap<String, Object>();
				hashmap.put("messageId", group.getMessageId());
				for (UserAppDto aDto : list) {
					hashmap.put("userId", aDto.getUserId());
					pnsUserMessageDao.updateByHql("DELETE_PNS_USER_BY_USER_ID",
							hashmap);
				}
				// 删除关系
				pnsUserGroupDao.updateByHql("DELETE_GROUP_USER_BY_GROUP_ID",
						map);
				pnsGroupDao.updateByHql("DELETE_GROUP_BY_NAME", map);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 通过medsageId 查找group
	 * 
	 * @param appId
	 * @param messageId
	 * @return
	 */
	public List<PnsGroup> getGroupByMessageId(Integer appId, Integer messageId) {
		Map<String, Object> map = new HashMap<String, Object>();
		String sql = "select t from PnsGroup t where t.messageId=:messageId and t.buildPlatform=:buildPlatform and t.appId=:appId";
		map.put("buildPlatform", BUILD_PLATFORM);
		map.put("appId", appId);
		map.put("messageId", messageId);
		List<PnsGroup> groupInfo = pnsGroupDao.findByHql(sql, 0, 0, map, null);
		return groupInfo;
	}

	public void updateMessageStatus(Integer messageId) {
		try {
			PnsMessage pmsg = pnsMessageDao.get(messageId);
			pmsg.setMessageStatus(0);
			pnsMessageDao.update(pmsg);
			String sql = "select t from PnsUserMessage t where t.messageId= :messageId ";
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("messageId", messageId);
			List<PnsUserMessage> pnsMessageList = pnsUserMessageDao.findByHql(
					sql, 0, 0, map, null);
			if (pnsMessageList != null && pnsMessageList.size() > 0) {
				for (PnsUserMessage pnsMessage : pnsMessageList) {
					pnsMessage.setMessageStatus(0);
					pnsUserMessageDao.update(pnsMessage);
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
